'''
Created on Feb 14, 2011

@author: oabalbin
'''
import re
from optparse import OptionParser
def read_file(input_file_name,out_file_name):
    '''
    Just change the spaces of a line for tabs
    It is currently used to process the dbSNP
    processed file, which contains spaces instead
    of tabs as field separator
    '''
    input_file = open(input_file_name)
    outfile=open(out_file_name,'w')
    
    for l in input_file:

        if l.startswith('#'):
            outfile.write(l)
            continue
        if l.startswith('MT'):
            fields = l.strip('\n').replace(',','$').split('\t')
            chr=fields[0].replace('MT','chrM')
            fields.pop(0)
            fields.insert(0,chr)
            oline = ",".join(fields).replace(',','\t')
            outfile.write(oline.replace('$',',')+'\n')
            continue
    
    input_file.close()

    input_file = open(input_file_name)
    for l in input_file:
        fields=l.strip('\n').replace(',','$').split('\t')
        if l.startswith('#') or l.startswith('MT') or (re.search('random',fields[0]) is not None) or \
           (re.search('hap',fields[0]) is not None) or (re.search('PAR',fields[0]) is not None):
            continue
        
        chr="chr"+fields[0]
        fields.pop(0)
        fields.insert(0,chr)
        oline = ",".join(fields).replace(',','\t')
        outfile.write(oline.replace('$',',')+'\n')
       
    outfile.close()
    

if __name__ == '__main__':
        
    optionparser = OptionParser("usage: %prog [options] ")
    optionparser.add_option("-f", "--query_vcf_file", dest="query_vcf_file",
                            help="query_vcf_file")

    (options, args) = optionparser.parse_args()     
    outfile=options.query_vcf_file.replace('.vcf','_processed_04_05_11.vcf')
    read_file(options.query_vcf_file,outfile)
